<template>
  <div class="app-content-wrap report-content-wrap" :style="'minHeight:' + gHeight + 'px;'">
    <div class="g-content-title">统计报表查询</div>

    <!-- 搜索框 -->
    <el-form label-width="80px" size="small">
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="统计方式">
            <el-col>
              <el-select v-model="statisticalMethod" placeholder="请选择统计方式">
                <el-option v-for="item in countTypeArr" :key="item.countValue" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="选择月份">
            <el-col>
              <el-select v-model="form.date" placeholder="请选择月份">
                <el-option v-for="item in monthSelectArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="提交方式">
            <el-col>
              <el-select v-model="form.submitType" placeholder="请选择提交方式">
                <el-option v-for="item in submitTypeArr" :key="item.submitTypeValue" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="所属" prop="deptId">
            <areaSelect :selectModel="form.deptId" :areaIds="areaIds" @onAreaChange="onAreaChange" hideThird="true"></areaSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择场景" prop="moduleId">
            <sceneSelect :selectModel="form.moduleId" :modTypes="modTypes" @onSceneChange="onSceneChange" :deptId="form.deptId"></sceneSelect>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="15">
        <el-form-item style="padding-left:15px">
          <el-button type="primary" icon="el-icon-search" @click="onDaySubmit" v-show="searchByDayBtn">按日搜索</el-button>
          <el-button style="margin:0" type="primary" icon="el-icon-search" @click="onMonthSubmit" v-show="searchByMonthBtn">按月搜索</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <!-- 日历 -->
    <div v-show="showCalender" class="calendar-box">
      <div class="title">{{calendarTitle}}</div>
      <calendar
        :events="calendar1.events"
        :lunar="calendar1.lunar"
        :value="calendar1.value"
        :begin="calendar1.begin"
        :end="calendar1.end"
        :weeks="calendar1.weeks"
        :months="calendar1.months"
        @select="calendar1.select"
        @selectMonth="calendar1.selectMonth"
      ></calendar>
    </div>

    <!-- 列表 -->
    <div v-show="showList" class="alarm-list">
      <div class="title">
        {{alarmListTitle}}
        <span class="list-download">
          <a :href="listDownloadUrl">下载全部</a>
        </span>
      </div>

      <el-table :data="tableData" stripe border class="el-table-body">
        <el-table-column prop="eventId" label="事件编号" min-width="180"></el-table-column>
        <el-table-column prop="moduleName" label="场景" min-width="230"></el-table-column>
        <el-table-column prop="eventTime" label="报警时间" min-width="200"></el-table-column>
        <el-table-column prop="areaName" label="所属" min-width="180"></el-table-column>
        <el-table-column prop="submitType" :formatter="submitTypeToText" label="提交类型"></el-table-column>
        <el-table-column prop="eventState" :formatter="eventStateToText" label="处理状态"></el-table-column>
      </el-table>

      <el-pagination
        background
        @current-change="changeEventTable"
        :current-page.sync="form.page"
        :page-size="form.limit"
        layout="total, prev, pager, next,jumper"
        :total="totalCount"
        class="el-page-body"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import areaSelect from '../../components/common/select/area'
import SceneSelect from '../../components/common/select/scene'
import Calendar from '../../assets/scripts/plugins/calendar/calendar.vue'
// import calendar from '../../assets/scripts/plugins/calendar/calendar'

export default {
  name: 'eventSearch',
  components: {
    areaSelect,
    SceneSelect,
    Calendar
  },

  data () {
    let _this = this
    return {
      gHeight: this.$store.state.gHeight,
      listDownloadUrl: '', // 列表下载地址
      calendar1: {
        value: [], // 默认日期
        lunar: false, // 显示农历
        weeks: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
        months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
        events: {},
        selectMonth (month, year) {
        },
        select (value) {
          let currFullDate = _this.convertFullDate(value) // 日期格式转换
          _this.showList = true // 显示列表
          _this.form.page = 1
          _this.getDayReportList(currFullDate)
        }
      },
      calendarTitle: '2018年-月报警数据统计',
      alarmListTitle: '2018年-月-日报警数据统计',
      showCalender: true, // 初始显示日历
      showList: false,
      areaIds: {
        areaId1: '', // 所属1级
        areaId2: '', // 所属2级
        areaId3: '' // 所属3级
      },
      modTypes: {
        modType1: '', // 场景分类
        modType2: '' // 场景子分类
      },
      form: {
        date: '', // 选择年月
        deptId: '', // 所属
        supModuleId: '', // 一级场景Id
        moduleId: '', // 二级场景Id
        submitType: '', // 提交方式
        page: 1, // 当前页数
        limit: 10 // 每页显示数量
      },
      countTypeArr: [
        {
          value: '1',
          label: '按日统计'
        }, {
          value: '2',
          label: '按月统计'
        }],
      monthSelectArr: [
        {
          value: '1',
          label: ''
        }, {
          value: '2',
          label: ''
        }, {
          value: '3',
          label: ''
        }
      ],
      submitTypeArr: [
        {
          value: '',
          label: '全部'
        }, {
          value: '1',
          label: '自动'
        }, {
          value: '2',
          label: '手动'
        }
      ],
      statisticalMethod: '', // 统计方式
      searchByDayBtn: true, // 初始显示'按日搜索'按钮
      searchByMonthBtn: false, // 初始隐藏'按月搜索'按钮
      tableData: [], // 列表数据
      totalCount: 0 // 列表总页数
    }
  },

  mounted: function () {
    this.init()
  },

  watch: {
    // 监听‘统计方式’下拉框变化，与‘选择月份’下拉框做联动
    statisticalMethod (val, oldVal) {
      if (val === '1') { // 按日查
        this.$data.searchByDayBtn = true
        this.$data.searchByMonthBtn = false
        this.getMonthOption(0) // 加载列表
        this.form.date = this.$data.monthSelectArr[0].value // 初始选中select第一项
      } else if (val === '2') { // 按月查
        this.$data.searchByDayBtn = false
        this.$data.searchByMonthBtn = true
        this.getMonthOption(1) // 加载列表
        this.form.date = this.$data.monthSelectArr[0].value // 初始选中select第一项
      }
    }
  },

  methods: {
    // 初始化
    init () {
      // this.getReportList();   //初始加载报表列表
      this.$data.statisticalMethod = '按日统计' // 初始‘统计方式’选中项
      this.getMonthOption(0) // 初始加载下拉框月份
      this.form.date = this.$data.monthSelectArr[0].value
      this.searchCalendarDay() // 初始加载日历每天报警数据 和 当天报警列表
    },
    // 获取下拉菜单月份
    getMonthOption: function (reduceNum) {
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1

      for (let i = 0; i < 3; i++) {
        let myMonth = month - i - reduceNum
        let myYear = year
        if (myMonth === 0) {
          myMonth = 12
          myYear = myYear - 1
        } else if (myMonth < 0) {
          myMonth = 12 + (month - i - reduceNum) % 12
          myYear = myYear - parseInt(Math.ceil(i / 12))
        }
        myMonth = myMonth < 10 ? '0' + myMonth : myMonth
        this.$data.monthSelectArr[i].value = myYear + '' + myMonth
        this.$data.monthSelectArr[i].label = myYear + '年' + myMonth + '月'
      }
    },
    // 提交表单(按日查询)
    onDaySubmit () {
      this.showList = false // 隐藏列表
      this.showCalender = true // 显示日历
      // 改变日历当前选定月份
      let currentFullDate = this.form.date // 日期选择框当前所选日期
      let currentYear = currentFullDate.substr(0, 4) // 选中的年份
      let currentMonth = currentFullDate.substr(4, 6) // 选中的月份
      // this.$data.calendar1.selectMonth(currentMonth,currentYear);
      this.$data.calendar1.value = [currentYear, currentMonth]
      this.searchCalendarDay() // 加载日历每天报警数据
    },
    // 提交表单(按月查询)
    onMonthSubmit () {
      this.form.page = 1
      this.showList = true // 显示列表
      this.showCalender = false // 隐藏日历
      let currentFullDate = this.form.date // 日期选择框当前所选日期
      this.getReportList(currentFullDate)
    },
    // 查询日历上每天的数据
    searchCalendarDay: function () {
      let _this = this
      let url = this.$base.getUrl('getStatisticCountByDay')

      // 场景id取select中最低层级所选中的值
      let modType1 = ''
      let modType2 = ''
      if (this.modTypes.modType2) {
        modType2 = this.modTypes.modType2
        modType1 = this.modTypes.modType1
      } else {
        modType1 = this.modTypes.modType1
      }
      this.form.supModuleId = modType1
      this.form.moduleId = modType2

      let params = {
        url: url,
        data: this.form
      }
      this.$store.dispatch('getForm', params).then((res) => {
        _this.updateCalendarData(res) // 更新日历每日报警数据
      })
    },
    // 提交类型转换成文字
    submitTypeToText: function (row) {
      return this.$base.getNameByConst('select', 'submitType', row.submitType)
    },
    // 处理状态转换成文字
    eventStateToText: function (row) {
      return this.$base.getNameByConst('select', 'eventState', row.eventState)
    },
    // 切换页码
    changeEventTable: function (val) {
      this.form.page = val
      let currType = this.statisticalMethod
      if (currType === '按日统计' || currType === '1') {
        let currentDay = document.querySelector('.calendar .selected span').innerHTML
        if (currentDay < 10) currentDay = '0' + currentDay
        let currentFullDate = this.form.date // 日期选择框当前所选日期
        let currValue = currentFullDate + '' + currentDay
        this.getDayReportList(currValue, this.form.page)
      } else {
        let currentFullDate = this.form.date // 日期选择框当前所选日期
        this.getReportList(currentFullDate)
      }
    },
    // 按月查询列表 方法
    getReportList: function (postFullDate) {
      let _this = this
      let url = this.$base.getUrl('getStatisticInfoList')

      // 场景id取select中最低层级所选中的值
      let modType1 = ''
      let modType2 = ''
      if (this.modTypes.modType2) {
        modType2 = this.modTypes.modType2
        modType1 = this.modTypes.modType1
      } else {
        modType1 = this.modTypes.modType1
      }
      this.form.supModuleId = modType1
      this.form.moduleId = modType2

      let params = {
        url: url,
        data: this.form
      }
      this.$store.dispatch('getForm', params).then((res) => {
        let data = res.page
        if (data.list) {
          _this.tableData = data.list
        } else {
          _this.tableData = []
        }
        _this.totalCount = data.totalCount
      })

      // 设置列表标题
      this.$data.alarmListTitle = postFullDate.substr(0, 4) + '年' + postFullDate.substr(4, 2) + '月 报警数据列表'
      this.getDownloadUrl(postFullDate, this.form.deptId, this.form.supModuleId, this.form.moduleId, this.form.submitType)
    },
    // 按日查询列表
    getDayReportList: function (postFullDate, currPage) {
      let _this = this
      let url = this.$base.getUrl('getStatisticInfoList')

      // 场景id取select中最低层级所选中的值
      let modType1 = ''
      let modType2 = ''
      if (this.modTypes.modType2) {
        modType2 = this.modTypes.modType2
        modType1 = this.modTypes.modType1
      } else {
        modType1 = this.modTypes.modType1
      }
      this.form.supModuleId = modType1
      this.form.moduleId = modType2

      let params = {
        url: url,
        data: {
          'yyyyMMdd': postFullDate,
          'deptId': _this.form.deptId,
          'supModuleId': _this.form.supModuleId,
          'moduleId': _this.form.moduleId,
          'submitType': _this.form.submitType,
          'page': currPage, // 当前页数
          'limit': 10 // 每页显示数量
        }
      }
      this.$store.dispatch('getForm', params).then((res) => {
        let data = res.page
        if (data.list) {
          _this.tableData = data.list
        } else {
          _this.tableData = []
        }
        _this.totalCount = data.totalCount
      })

      // 设置列表标题
      this.$data.alarmListTitle = postFullDate.substr(0, 4) + '年' + postFullDate.substr(4, 2) + '月' + postFullDate.substr(6, 8) + '日 报警数据列表'

      this.getDownloadUrl(postFullDate, this.form.deptId, this.form.supModuleId, this.form.moduleId, this.form.submitType)
    },
    // 更新日历每日报警数据
    updateCalendarData: function (daysAlarmDataArr) {
      // 获取选定的该月天数

      let currentFullDate = this.form.date // 日期选择框当前所选日期
      let currentYear = currentFullDate.substr(0, 4) // 选中的年份
      let currentMonth = currentFullDate.substr(4, 6) // 选中的月份
      let currentMonthRemoveZero = currentMonth.replace(/^0/, '') // 月份去零  例：06 => 6
      let myDay = new Date(currentYear, currentMonth, 0) // 该月最后一天的日期
      let dayCount = myDay.getDate() + 1 // 该月天数

      // 判断选中的月份，如果是当月，忽略今天之后的数据
      let lastDate = new Date() // 获取系统当前时间
      let lastYear = lastDate.getFullYear() // 系统年份
      let lastMonth = lastDate.getMonth() + 1 // 系统月份
      let lastDayCount = lastDate.getDate() // 该月天数
      let lastFullDate = lastYear + '' + lastMonth // 当月 年月
      let myFullDate = currentYear + '' + currentMonthRemoveZero // 选中的年月

      if (lastFullDate === myFullDate) { // 当前年月 = 选中的年月
        dayCount = lastDayCount + 1 // 只显示今天及之前的告警数据
        this.$data.calendar1.value = [lastYear, lastMonth, lastDayCount] // 日历表初始选中今天
      }

      // 改变日历的title
      this.$data.calendarTitle = currentYear + '年' + currentMonthRemoveZero + '月 报警数据统计'

      // 将接口数据与该月每天数据一一对应
      let myCalendarAlarmDate = {}
      for (let i = 1; i < dayCount; i++) {
        myCalendarAlarmDate[+currentYear + '-' + currentMonthRemoveZero + '-' + i] = '' + daysAlarmDataArr['day' + (i)]
      }
      this.calendar1.events = myCalendarAlarmDate // 更新日历的每日告警数据
    },
    // 日期格式转换
    convertFullDate (setDate) {
      // 取得所点击的日期  yyyymmdd
      let currYear = setDate[0]
      let initMonth = setDate[1]
      let initDay = setDate[2]
      let currMonth = initMonth.toString().length === 1 ? '0' + initMonth : initMonth // 月份补零
      let currDay = initDay.toString().length === 1 ? '0' + initDay : initDay // 天数补零
      return currYear + '' + currMonth + '' + currDay
    },

    // 所属变化时
    onAreaChange (val) {
      this.form.deptId = val
    },
    onSceneChange (val) {
      this.form.moduleId = val
    },

    // 获取下载请求地址
    getDownloadUrl (queryDate, deptId, supModuleId, moduleId, submitType) {
      let downloadUrl = this.$base.getUrl('reportExl')
      const type = !this.searchByMonthBtn ? 'yyyyMMdd' : 'date'
      this.listDownloadUrl = downloadUrl + '?' + type + '=' + queryDate + '&deptId=' + deptId + '&supModuleId=' + supModuleId + '&moduleId=' + moduleId + '&submitType=' + submitType
    }

  }

}
</script>
<style lang="less" scoped>
.el-table {
  width: auto !important;
  text-align: center;
  margin: 10px;
}

.el-table /deep/ th {
  text-align: center;
}

.el-pagination {
  margin: 0 10px;
}

.calendar-box {
  margin: 10px 30px;
}

.calendar-box .title,
.alarm-list .title {
  text-align: center;
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 12px;
}

.alarm-list {
  padding-top: 10px;
}

.alarm-list .title {
  padding-left: 106px;
}

.list-download {
  a {
    margin-right: 30px;
    margin-top: -4px;
    padding: 2px 10px;
    border-color: #409eff;
    color: #fff;
    background-color: rgb(64, 158, 255);
    text-decoration: none;
    float: right;
    border-radius: 2px;
  }
}
</style>
